import { Redirect, Route, Switch } from "react-router-dom";
import type { FC, ComponentType } from "react";

import Home from "./views/Home";
import About from "./views/About";
import Order from "./views/Order";
import Login from "./views/Login";

/**
 *
 * 示例
 *
 *    <RouteAuth path="/order" component={Order} />
 */
interface RouteAuthProps {
  path: string;
  component: ComponentType;
}
const RouteAuth: FC<RouteAuthProps> = ({ path, component: Component }) => {
  return (
    <Route
      path={path}
      render={(props) => {
        // 处理 fullPath
        const fullPath = props.location.pathname + props.location.search;
        // 获取 token
        const token = window.localStorage.getItem("token");
        if (token) {
          // 登录了
          return <Component />;
        } else {
          // 未登录
          return <Redirect to={`/login?redirect=${fullPath}`} />;
        }
      }}
    />
  );
};

export default function App() {
  function handleLogout() {
    localStorage.removeItem("token");
  }

  return (
    <div>
      <button onClick={handleLogout}>退出登录</button>
      <hr />
      <Switch>
        <Route path="/home" component={Home} />
        <Route path="/login" component={Login} />
        <RouteAuth path="/about" component={About} />
        <RouteAuth path="/order" component={Order} />

        {/* <Route
          path="/about"
          render={(props) => {
            // 处理 fullPath
            const fullPath = props.location.pathname + props.location.search;
            // 获取 token
            const token = window.localStorage.getItem("token");
            if (token) {
              // 登录了
              return <About />;
            } else {
              // 未登录
              return <Redirect to={`/login?redirect=${fullPath}`} />;
            }
          }}
        />
        <Route
          path="/order"
          render={(props) => {
            // 处理 fullPath
            const fullPath = props.location.pathname + props.location.search;
            // 获取 token
            const token = window.localStorage.getItem("token");
            if (token) {
              // 登录了
              return <Order />;
            } else {
              // 未登录
              return <Redirect to={`/login?redirect=${fullPath}`} />;
            }
          }}
        /> */}
      </Switch>
    </div>
  );
}
